package com.wennn.top.web.product;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.wennn.top.common.util.BeanUtils;
import com.wennn.top.common.vo.IResult;
import com.wennn.top.core.mybatis.vo.BEntity;
import com.wennn.top.core.util.CoreConst;
import com.wennn.top.core.util.ErrorHelper;
import com.wennn.top.security.util.ContextUtil;
import com.wennn.top.shop.biz.order.entity.YxStoreCart;
import com.wennn.top.shop.biz.order.service.IYxStoreCartService;
import com.wennn.top.shop.biz.product.entity.YxStoreProduct;
import com.wennn.top.shop.biz.product.service.IYxStoreProductService;
import com.wennn.top.util.DateUtil;
import com.wennn.top.web.product.vo.CartInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 购物车
 * 用户和商品的关联关系
 * @author: wennn
 * @date: 7/5/20
 */

@RestController
@RequestMapping("/cart")
@Api(tags = "购物车")
public class StoreCartRest {

    @Autowired
    IYxStoreCartService iYxStoreCartService;

    @Autowired
    IYxStoreProductService iYxStoreProductService;

    @ApiOperation("添加购物车")
    @PostMapping(value = "/add/{productId}")
    public IResult addCart(@PathVariable("productId") Integer productId,
                           @RequestParam(value = "cartNum",defaultValue = "1") int cartNum,
                           @RequestParam(value = "attrUnique",defaultValue = "0") String attrUnique,
                           @RequestParam(value = "type",defaultValue = "0") String type
    ) {

        if(type.equals("1")){ // 当直接购买的话

        }
        // 如果 productId attrUnique 存在 则添加数量
        LambdaQueryWrapper<YxStoreCart> tWrapper = Wrappers.lambdaQuery(YxStoreCart.class);
        tWrapper.eq(YxStoreCart::getProductId,productId).eq(YxStoreCart::getProductAttrUnique,attrUnique);


        YxStoreCart yxStoreCart = Optional.ofNullable(iYxStoreCartService.getOne(tWrapper)).orElseGet(()->new YxStoreCart());

        if(Objects.isNull(yxStoreCart.getId())){
            yxStoreCart.setUid(ContextUtil.getUser().getId());
            yxStoreCart.setType("product");
            yxStoreCart.setProductId(productId);
            yxStoreCart.setProductAttrUnique(attrUnique);// 属性标示
            yxStoreCart.setCartNum(cartNum);             // 收藏数量
            yxStoreCart.setAddTime(DateUtil.nowIntTime());
            yxStoreCart.setIsPay(Boolean.FALSE);
            yxStoreCart.setIsDel(Boolean.FALSE);
            yxStoreCart.setIsNew(Boolean.FALSE);
            iYxStoreCartService.save(yxStoreCart);
        }else{
            yxStoreCart.setCartNum(yxStoreCart.getCartNum()+cartNum);
            iYxStoreCartService.updateById(yxStoreCart);
        }
        return IResult.ok(yxStoreCart.getId());
    }


    @ApiOperation("删除购物车")
    @PostMapping(value = "/del")
    public IResult removeCart(@RequestBody String[] ids) {
        boolean b = iYxStoreCartService.removeByIds(Arrays.asList(ids));
        return b ? IResult.ok() : IResult.fail(CoreConst.FAIL, "删除失败");
    }


    @ApiOperation("获取当前登陆人购物车信息")
    @PostMapping(value = "/getAll")
    public IResult getAllCart() {
        LambdaQueryWrapper<YxStoreCart> cartWrapper = Wrappers.lambdaQuery();
        cartWrapper.eq(YxStoreCart::getUid, ContextUtil.getUser().getId());
        List<YxStoreCart> list = iYxStoreCartService.list(cartWrapper);

        List<CartInfoVo> result = list.parallelStream().map(c ->BeanUtils.copy(c, CartInfoVo.class)).peek(cart -> {
            YxStoreProduct product = iYxStoreProductService.getById(cart.getProductId());
            cart.setProduct(product);
        }).collect(Collectors.toList());

        Map map = Maps.newHashMap();
        map.put("valid",result);    // 有效的
        map.put("invalid","");  // 过期的
        return IResult.ok(map);
    }

    @ApiOperation(value = "获取当前用户购物车数量",notes = "商品详情页或者个人中心页面显示")
    @PostMapping(value = "/count")
    public IResult count() {
        LambdaQueryWrapper<YxStoreCart> cartWrapper = Wrappers.lambdaQuery();
        cartWrapper.eq(YxStoreCart::getUid, ContextUtil.getUser().getId());
        int count = iYxStoreCartService.count(cartWrapper);
        return IResult.ok(count);
    }


    @ApiOperation(value = "修改购物车物品数量",notes = "购物车里修改商品数量")
    @PostMapping(value = "/num/{id}")
    public IResult num(@PathVariable("id") int id,@RequestParam("num") int num) {
        LambdaQueryWrapper<YxStoreCart> cartWrapper = Wrappers.lambdaQuery();
        cartWrapper.eq(YxStoreCart::getUid, ContextUtil.getUser().getId()).eq(BEntity::getId,id);
        YxStoreCart entity = new YxStoreCart();
        entity.setCartNum(num);
        boolean b = iYxStoreCartService.update(entity,cartWrapper);
        return ErrorHelper.update(b);
    }


}
